function Promise(executor) {
    this.PromiseState = 'pending';
    this.PromiseResult = undefined;
    this.callbacks = [];
    const resolve = (value) => {
        if (this.PromiseState !== 'pending') return;
        this.PromiseState = 'fulfilled';
        this.PromiseResult = value;
        if (this.callbacks.length) {
            this.callbacks.forEach(item => {
                item.success();
            })
        }
    }
    const reject = (reason) => {
        if (this.PromiseState !== 'pending') return;
        this.PromiseState = 'rejected';
        this.PromiseResult = reason;
        if (this.callbacks.length) {
            this.callbacks.forEach(item => {
                item.fail();
            })
        }
    }
    try {
        executor(resolve, reject);
    } catch (e) {
        reject(e);
    }
}
Promise.prototype.then = function (onResolve, onReject) {
    if (typeof onReject !== 'function') {
        // 失败回调默认值：失败回调有一个基本要求，将promise失败的状态和结果值向下传递
        onReject = reason => new Promise((resolve, reject) => reject(reason));
    }
    if (typeof onResolve !== 'function') {
        // 成功回调默认值：成功回调有一个基本要求，将promise成功的状态和结果值向下传递
        onResolve = value => value;
    }
    return new Promise((resolve, reject) => {
        const changeState = (fn) => {
            // 捕获then方法成功或失败回调函数中抛出的异常
            try {
                setTimeout(() => {
                    let rs = fn(this.PromiseResult);
                    if (rs instanceof Promise) {// rs 是Promise
                        rs.then(resolve, reject)
                    } else {// rs不是Promise
                        resolve(rs);
                    }
                })
            } catch (e) {
                reject(e)
            }
        }
        if (this.PromiseState === 'fulfilled') {
            changeState(onResolve)
        }
        if (this.PromiseState === 'rejected') {
            changeState(onReject)
        }
        if (this.PromiseState === 'pending') {
            this.callbacks.push({
                success: () => {
                    changeState(onResolve)
                },
                fail: () => {
                    changeState(onReject)
                }
            })
        }
    })
}
// catch用来指定失败的回调，所以调用一下then方法，只指定失败的回调即可
Promise.prototype.catch = function (onReject) {
    return this.then(null, onReject);
}


/**
 *  返回一个Promise对象，对象的状态和结果值情况如下：
 * 1. value 是 非 Promise对象： fulfilled  value
 * 2. value 是Promise对象   ：  你成功我成功，你成功的结果.....
 * 
 */
Promise.resolve = function(value){
    return new Promise((resolve, reject)=>{
        if(value instanceof Promise){
            value.then(resolve, reject);
        }else{
            resolve(value);
        }
    })
}
/**
 * 返回一定是一个失败的promise
 */
Promise.reject = function(reason){
    return new Promise((resolve, reject)=>{
        reject(reason);
    });
}